# -*- coding: utf-8 -*-

import os
import sys
import logging
import json
import time
import configparser
import threading
#####################
from tcp_client import TCPClient
from message_handler import MessageHandler
import message_types_res as message_types
import app_common as app_com
import subscribe_image

class PyTcpClient:
    def __init__(self):
        logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',\
            level=logging.DEBUG)
        self.conf = {}
        self.msg_types = {}

    def config_prase(self, cfg_file):
        if not os.path.exists(cfg_file):
            logging.error("config file %s not exist", cfg_file)
            return -1

        cfg = configparser.ConfigParser()
        cfg.read(cfg_file, encoding="utf-8")
        self.conf = dict(cfg.items("client"))
        logging.debug("the config item: %s", self.conf)
        return 0

    # prase message types file
    def prase_message_types(self, type_file):
        if not os.path.exists(type_file):
            logging.error("type file %s not exist", type_file)
            return -1

        with open(type_file, "r") as file:
            types = json.load(file)
            logging.debug("message types content is %s", types)
            
            # syncBytes hex to dec, save to msg_types dict
            sync_bytes_list = types[message_types.kSyncBytes].split(",")
            hex_str = sync_bytes_list[3][2:] + sync_bytes_list[2][2:] + sync_bytes_list[1][2:] + sync_bytes_list[0][2:]
            self.msg_types[message_types.kSyncBytes] = int(hex_str, 16)

            # message type hex to dec, save to msg_types dict
            for key, value in types[message_types.kMessageTypes].items():
                # check whether message type reading from type file have been predefined
                # if key in message_types:
                message_type_list = value.split(",")
                hex_str = message_type_list[3][2:] + message_type_list[2][2:] + message_type_list[1][2:] + message_type_list[0][2:]
                self.msg_types[key] = int(hex_str, 16)
                # else:
                #     logging.error("prase type file failed, the %s is exist", key)
                #     return -1
            logging.debug("message types is %s", self.msg_types)
            return 0

        logging.error("open type file failed: %s", type_file)
        return -2

    def start(self, cfg_file, type_file):
        ret = self.config_prase(cfg_file)
        if ret != 0:
            logging.error("prase config file faild")
            return -1

        ret = self.prase_message_types(type_file)
        if ret != 0:
            logging.error("prase type file failed")
            return -2

        self.client = TCPClient(self.conf, self.msg_types)
        self.msg_handler = MessageHandler(self.client.cmd_queue, self.conf, self.msg_types, self.client)
        self.msg_handler.start()
        self.client.start()
        return 0
    
    def start_subscribe_image(self):
        sub = threading.Thread(target=subscribe_image.subscribe_image)
        sub.setDaemon(True)
        sub.start()


if __name__ == "__main__":
    client = PyTcpClient()
    client.start("conf/app.cfg", "conf/message_types.json")
    client.start_subscribe_image()
    logging.debug("main start!")
    Q = input("Enter q to quit the app!\n")
    if Q.lower() == 'q':
        try:
            sys.exit(0)
        except:
            print('Program is dead.')
        finally:
            print('clean-up')

    
